package http_middleware

import (
	"ce-cloud/pkg/data_source/d_RAM"
	"ce-cloud/pkg/log"
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
)

// Interceptor 非法请求拦截器
type Interceptor struct{}

const interceptKey = "interceptTimes:%s"

// 3秒内超过10次请求，将会把多余的请求拦截掉

const interceptTimes = int(10)
const interceptWaitTime = int64(3)

func (i Interceptor) Check(c *gin.Context) {
	remoteAddr := c.ClientIP()
	key := fmt.Sprintf(interceptKey, remoteAddr)
	data, has := d_RAM.Data.Get(key)
	if has {
		times := data.(int)
		if times > interceptTimes {
			log.Warnf("remoteAddr:{%s} 请求过于频繁！！！, 当前次数：%d", remoteAddr, times)
			c.JSON(http.StatusTooManyRequests, gin.H{"msg": "Error."})
			c.Abort()
		}
		d_RAM.Data.SetWithTTL(key, times+1, interceptWaitTime)
		return
	} else {
		d_RAM.Data.SetWithTTL(key, int(1), interceptWaitTime)
	}
	c.Next()
}
